public class BuildTree {
    // leetcode 从前序与中序遍历序列构建二叉树
    // https://leetcode.cn/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/?envType=study-plan-v2&envId=top-100-liked
    private int index = 0;
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return buildTreeChild(preorder, inorder, 0, preorder.length-1);
    }

    private TreeNode buildTreeChild(int[] preorder, int[] inorder, int left, int right) {
        if (left > right) return null;
        TreeNode root = new TreeNode(preorder[index]);
        int pivot = findIndex(inorder, preorder[index++]);
        root.left = buildTreeChild(preorder, inorder, left, pivot-1);
        root.right = buildTreeChild(preorder, inorder, pivot+1, right);
        return root;
    }

    private int findIndex(int[] inorder, int target) {
        for (int i = 0; i < inorder.length; i++) {
            if (inorder[i] == target) return i;
        }
        return -1;
    }
}
